DECLARE @id INT
DECLARE @amount INT
DECLARE @saleAmount INT
DECLARE @inAmount INT
DECLARE @outAmount INT

DECLARE CUR_ CURSOR LOCAL FAST_FORWARD FOR 
SELECT Id, Amount FROM Product
OPEN CUR_
 
FETCH NEXT FROM CUR_
INTO @id, @amount
  

WHILE @@FETCH_STATUS = 0
BEGIN

    SELECT @saleAmount = SUM(ISNULL(Amount, 0)) FROM BillDetail
						WHERE BillDetail.ProductId = @id
    
    
    SET @saleAmount = ISNULL(@saleAmount, 0)
    --PRINT @saleAmount
    
    SELECT @inAmount = SUM(ISNULL(Amount, 0)) FROM InProdDetail InProd
						WHERE InProd.ProductId = @id
	
	SET @inAmount = ISNULL(@inAmount, 0)
	
	--PRINT @inAmount					
	SELECT @outAmount = SUM(ISNULL(Amount, 0)) FROM OutProdDetail OutProd
						WHERE OutProd.ProductId = @id
	
	SET @outAmount = ISNULL(@outAmount, 0)
	--PRINT @outAmount
	
	
	IF @amount <> (@inAmount - @saleAmount - @outAmount) BEGIN
		PRINT @id
		--PRINT 'aaa'
		-- UPDATE Product Amount
		UPDATE Product
		SET Amount = (@inAmount - @saleAmount - @outAmount)
		WHERE Id = @id
	END
    FETCH NEXT FROM CUR_ INTO @id, @amount 

END

CLOSE CUR_
DEALLOCATE CUR_
